﻿<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="FormTableManager.aspx.cs"
    Inherits="ZX.WebApp.DesignForm.FormTableManager" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <!--CSS file (default YUI Sam Skin) -->
    <link rel="stylesheet" type="text/css" href="../scripts/yui_2.9.0/build/reset-fonts-grids/reset-fonts-grids.css" />
    <link rel="stylesheet" type="text/css" href="../scripts/yui_2.9.0/build/container/assets/skins/sam/container.css" />
    <link rel="stylesheet" type="text/css" href="../scripts/yui_2.9.0/build/menu/assets/skins/sam/menu.css" />
    <link rel="stylesheet" type="text/css" href="../scripts/yui_2.9.0/build/button/assets/skins/sam/button.css" />
    <link rel="stylesheet" type="text/css" href="../scripts/yui_2.9.0/build/resize/assets/skins/sam/resize.css" />
    <link rel="stylesheet" type="text/css" href="../scripts/yui_2.9.0/build/layout/assets/skins/sam/layout.css" />
    <link type="text/css" rel="stylesheet" href="../Scripts/yui_2.9.0/build/datatable/assets/skins/sam/datatable.css" />
    <!--begin custom header content for this example-->
    <style type="text/css">
    .yui-skin-sam table {
	    width: 100%;
    }
    
    #button-example-form fieldset, 
    #button-example-form fieldset div {

        border: 2px groove #ccc;
        margin: .5em;
        padding: .5em;

    }

    .yui-button#pushbutton2 button,
    .yui-button#pushbutton5 button, 
    .yui-button .Add button {
        background: url(../button/assets/add.gif) center center no-repeat;
        text-indent: -4em;
        overflow: hidden;
        padding: 0 .75em;
        width: 2em;
        *margin-left: 4em;   /* IE only */
        *padding: 0 1.75em;  /* IE only */

    }
    
    .yui-button#pushbutton3 button,
    .yui-button#pushbutton6 button, 
    .yui-button#pushbutton9 button {

        padding-left: 2em;
        background: url(../button/assets/add.gif) 10% 50% no-repeat;
    
    }
    #container select,#container input
    {
        width:100%;
        min-width:5em;
    }
    
    
    #toolbar
    {
        border-bottom:1px solid #ccc;
        margin-bottom:3px;
    }
    .form
    {
        padding:5px;
    }
    
    .form select
    {
        width:120px;
    }
    
    
</style>
    <!--end custom header content for this example-->
    <!-- Dependencies -->
    <script type="text/javascript" src="../Scripts/yui_2.9.0/build/yahoo-dom-event/yahoo-dom-event.js"></script>
    <script type="text/javascript" src="../Scripts/yui_2.9.0/build/element/element-min.js"></script>
    <script type="text/javascript" src="../Scripts/yui_2.9.0/build/datasource/datasource-min.js"></script>
    <!-- OPTIONAL: JSON Utility (for DataSource) -->
    <script type="text/javascript" src="../Scripts/yui_2.9.0/build/json/json-min.js"></script>
    <!-- OPTIONAL: Connection Manager (enables XHR for DataSource) -->
    <script type="text/javascript" src="../Scripts/yui_2.9.0/build/connection/connection-min.js"></script>
    <!-- OPTIONAL: Get Utility (enables dynamic script nodes for DataSource) -->
    <script type="text/javascript" src="../Scripts/yui_2.9.0/build/get/get-min.js"></script>
    <!-- OPTIONAL: Drag Drop (enables resizeable or reorderable columns) -->
    <script type="text/javascript" src="../Scripts/yui_2.9.0/build/dragdrop/dragdrop-min.js"></script>
    <!-- OPTIONAL: Calendar (enables calendar editors) -->
    <script type="text/javascript" src="../Scripts/yui_2.9.0/build/calendar/calendar-min.js"></script>
    <!-- Source files -->
    <script type="text/javascript" src="../Scripts/yui_2.9.0/build/datatable/datatable-min.js"></script>
    <script type="text/javascript" src="../scripts/yui_2.9.0/build/layout/layout-min.js"></script>
    <script type="text/javascript" src="../scripts/yui_2.9.0/build/button/button-min.js"></script>
    <script type="text/javascript" src="../scripts/yui_2.9.0/build/container/container-min.js"></script>
    <script type="text/javascript" src="../scripts/yui_2.9.0/build/resize/resize-min.js"></script>
    <script src="../Scripts/Appjs/model.TrSubjectInfo.js" type="text/javascript"></script>
    <script src="../Scripts/jquery-1.6.min.js" type="text/javascript"></script>
    <script src="../Scripts/jquery.json-2.2.min.js" type="text/javascript"></script>
    <script src="../Scripts/Jquery/jlinq/jlinq.js" type="text/javascript"></script>
    <script src="../Scripts/Jquery/DesignForm/DesignForm.Common.js" type="text/javascript"></script>
    <script src="DesignForm.js" type="text/javascript"></script>
</head>
<body class="yui-skin-sam">
    <div id="toolbar" style="padding: 5px;">
        <%--        <button type="button" id="btnOpen" class="yui-button yui-push-button" style="display: none">
            打开方案</button>--%>
        表名：<input id="txtTableName" type="text" onchange="" />
        说明：<input id="txtNotes" type="text" onchange="" />
        <button type="button" id="btnSave" style="display: none">
        </button>
        <button type="button" id="btnAddNew" class="yui-button yui-push-button">
            新增</button>
        <button type="button" id="btnDelete" class="yui-button yui-push-button">
            删除</button>
        
    </div>
    <div class="form" style="display: none">
        历史方案:<% =Solution %>
        方案名称:<input type="text" id="SolutionName" />
        是否默认:<input type="checkbox" id="IsDefault" /></div>
 
        <div id="container">
        </div>
   
    <form id="form2" action="../Extend/AjaxData/DataSave.aspx">
    <textarea style="display: none" id="jsonDataContent" rows="2" cols="2" name="jsonDataContent"></textarea>
    </form>
    <script type="text/javascript">
    // 字段信息
    var arrFieldInfo = <% =FieldInfo %>,
          arrOperation = [ { Text: "varchar", Value: "varchar" },
         { Text: "uniqueidentifier", Value: "uniqueidentifier" },
         { Text: "nvarchar", Value: "nvarchar" }, 
         { Text: "numeric", Value: "numeric" },
        { Text: "money", Value: "money" },
        { Text: "ntext", Value: "ntext" },
        { Text: "nchar", Value: "nchar" },
        { Text: "real", Value: "real" },
        { Text: "float", Value: "float" },
        { Text: "binary", Value: "binary" },
        { Text: "date", Value: "date" },
        { Text: "smalldatetime", Value: "smalldatetime" },
        { Text: "bigint", Value: "bigint" },
         { Text: "datetime", Value: "datetime"},
         {Text :"int", Value: "int" },
         {Text:"bit" , Value: "bit"} ,
         { Text: "char", Value: "char"},
         { Text: "image", Value: "image" } 
                 ],
          arrControlsType = [{ Text: "单行文本", Value: "textfield" },
         { Text: "多行文本", Value: "textarea" },
         { Text: "单选框", Value: "radio" },
         { Text: "复选框", Value: "checkbox" },
        { Text: "下拉选择框", Value: "select" },
        { Text: "日期", Value: "Date" },
        { Text: "时间", Value: "Time" },
        { Text: "隐藏", Value: "Hidden" },

        { Text: "部门", Value: "s" },
//        { Text: "内部用户", Value: "u" },
        { Text: "调岗控件", Value: "pos" },
        { Text: "跨门部门控件", Value: "dep" },
//        { Text: "职员", Value: "e" },

        { Text: "用户[登陆名]", Value: "6" },
        { Text: "多用户[登陆名]", Value: "5" },
        { Text: "不定期", Value: "workflowfell" }

     
//        { Text: "客户", Value: "m" },
//        { Text: "客户经理", Value: "v" },
//        { Text: "业绩归属", Value: "g" },
//        { Text: "客户总监", Value: "h" }
        ],
         arrOrAnd = [ { Text: " ", Value: " " },{ Text: "是", Value: "Y" }, { Text: "否", Value: "N" }],
        anObject = {'申请人':'Proposer', '所属分公司':'Filiale', '所属部门ID':'DeptID', '所属部门':'DeptName','所属岗位ID':'PostID','所属岗位':'PostName','申请时间':'CreatedTime', '流程模板ID':'WorkFlowId', '流程实例ID':'WorkFlowInsId', '流程模板任务ID':'WorkTaskId','流程任务实例ID':'WorkTaskInsId','标题':'bpmTitle'}, 
        mDataTable=null,
        QueryInstance=[<% =strJson %>],
        const_Table = "<% =Table  %>",
        const_EntityName="<% =EntityName %>",
        const_FunctionId="<% =FunctionID %>",
        const_BlankInstance = [<%=Instance%>],
        const_SysTable=<% =SysTable %>,
        const_SolutionList = <% =FieldList%>,
        
        const_TableName = "<%=TableName%>",
        fieldList=null,
        const_Tableid="",
        const_PrimaryKeyItems=null;
        myDataTable=null;

        isAddDefault="<%=isAddDefault %>";
      
        //格式化字段信息
        var formatField = function (elCell, oRecord, oColumn, sData) {
                var str1 = [];
                str1.push("<input type=\"text\" value=\"" + sData + "\"  name='FieldName' onchange='ChangeEvent(this);'");
                if(oRecord._oData.iSun_IsNew){
                  str1.push(" >");
                }else{str1.push(" disabled>");}
                
                elCell.innerHTML = str1.join("");
                
            };

        //格式化控件类型信息
        var formatControlsType = function (elCell, oRecord, oColumn, sData) {
            var str1 = [];
            var id = "id" + Math.random();
            str1.push("<select id='" + id + "' onchange='ChangeEvent(this);' name='ControlsType' >");
            
            for (var j = 0; j < arrControlsType.length; j++) {
                if (arrControlsType[j].Value == sData) {
                    str1.push("<option value='" + arrControlsType[j].Value + "' selected>" + arrControlsType[j].Text + "</option>");
                } else {
                    str1.push("<option value='" + arrControlsType[j].Value + "'>" + arrControlsType[j].Text + "</option>");
                }
            }
            str1.push("</select>");
            elCell.innerHTML = str1.join("");
        }

        var formatFiledType = function (elCell, oRecord, oColumn, sData) {
            var str1 = [];
            str1.push("<select name='FiledType' onchange='ChangeEvent(this);'");
             if(oRecord._oData.iSun_IsNew){
                str1.push(" >");
            }else{str1.push(" disabled>");}
            for (i = 0; i < arrOperation.length; i++) {
                //alert(arrOperation[i].Value+":"+sData);
                if(arrOperation[i].Value==sData){
                      
                    str1.push("<option value='" + arrOperation[i].Value + "' selected>" + arrOperation[i].Text + "</option>");
                }else{
                    str1.push("<option value='" + arrOperation[i].Value + "'>" + arrOperation[i].Text + "</option>");
                }
            } 
            str1.push("</select>");
                
            elCell.innerHTML = str1.join();
        }
        //格式化是否为空信息
        var formatIs_Null =  function(elCell, oRecord, oColumn, sData) {
            var str1 = [];
            var id = "id"+Math.random();
            str1.push("<select id='"+id+"' onchange='ChangeEvent(this);' name='Is_Null'");
            if(oRecord._oData.iSun_IsNew){
                str1.push(" >");
            }else{str1.push(" disabled>");}
            for (i = 0; i < arrOrAnd.length; i++) {
                if(arrOrAnd[i].Value == sData){
                str1.push("<option value='" + arrOrAnd[i].Value + "' selected>" + arrOrAnd[i].Text + "</option>");
                }else{
                str1.push("<option value='" + arrOrAnd[i].Value + "'>" + arrOrAnd[i].Text + "</option>");
                }
                    
            }
            str1.push("</select>");
            elCell.innerHTML = str1.join("");
        } 
        //格式化是否为主键信息
        var formatIs_ForeignKey =  function(elCell, oRecord, oColumn, sData) {
            var str1 = [];
            var id = "id"+Math.random();
            str1.push("<select id='"+id+"' onchange='ChangeEvent(this);' name='Is_ForeignKey'");
            if(oRecord._oData.iSun_IsNew){
                str1.push(" >");
            }else{str1.push(" disabled>");}
            for (i = 0; i < arrOrAnd.length; i++) {
                if(arrOrAnd[i].Value == sData){
                str1.push("<option value='" + arrOrAnd[i].Value + "' selected>" + arrOrAnd[i].Text + "</option>");
                }else{
                str1.push("<option value='" + arrOrAnd[i].Value + "'>" + arrOrAnd[i].Text + "</option>");
                }    
            }
            str1.push("</select>");
            elCell.innerHTML = str1.join("");
        } 
        //格式化左括符信息
        var formatLeftText = function (elCell, oRecord, oColumn, sData) {
            var str1 = [];
            str1.push("<input type=\"text\" value=\"" + sData + "\"  name='Left' onchange='ChangeEvent(this);'");
            if(oRecord._oData.iSun_IsNew){
                str1.push(" >");
            }else{str1.push(" disabled>");}
           elCell.innerHTML = str1.join("");
        }
        //格式化右括符信息
        var formatRightText = function (elCell, oRecord, oColumn, sData) {

            var str1 = [];
            str1.push("<input type=\"text\" value=\"" + sData + "\"  name='Right' onchange='ChangeEvent(this);'");
            if(oRecord._oData.iSun_IsNew){
                str1.push(" >");
            }else{str1.push(" disabled>");}
           elCell.innerHTML = str1.join("");
        }
        //格式化长度/精确度信息
        var formatLengthText = function (elCell, oRecord, oColumn, sData) {

            var str1 = [];
            str1.push("<input type=\"text\" value=\"" + sData + "\"  name='Length' onchange='ChangeEvent(this);'");
            if(oRecord._oData.iSun_IsNew){
                str1.push(" >");
            }else{str1.push(" disabled>");}
           elCell.innerHTML = str1.join("");
        }
        //格式化说明信息
        var formatNotesText = function (elCell, oRecord, oColumn, sData) {
            var str1 = [];
            str1.push("<input type=\"text\" value=\"" + sData + "\"  name='Notes' onchange='ChangeEvent(this);'");
            if(oRecord._oData.iSun_IsNew){
                str1.push(" >");
            }else{str1.push(" disabled>");}
           elCell.innerHTML = str1.join("");
        }
        //格式化排序信息
        var formatColSeqText = function (elCell, oRecord, oColumn, sData) {
            var str1 = [];
            str1.push("<input type=\"text\" value=\"" + sData + "\"  name='ColSeq' onchange='ChangeEvent(this);' >");
           elCell.innerHTML = str1.join("");
        }

       var formatCheckBoxText = function (elCell, oRecord, oColumn, sData) {
            var str1 = [];
            str1.push("<input type=\"checkbox\" value=\"" + sData + "\"  name='iSun_Selected'");
            if(oRecord._oData.iSun_IsNew){
                str1.push(" >");
            }else{str1.push(" disabled>");}
           elCell.innerHTML = str1.join("");
        }

    var myDataSource,AddDefaultProperty,myDataTable,AddPropertyByLength;
    //YAHOO创建表
    YAHOO.util.Event.addListener(window, "load", function () {

          var _sysTable=const_SysTable;
          var _txtNotes = YAHOO.util.Dom.get("txtNotes");
          _txtNotes.value=const_TableName;

          if(const_SysTable)
          {
            
            var _tableName = YAHOO.util.Dom.get("txtTableName");
             _tableName.value=const_Table
             const_Table=const_SysTable.TableName;
             if(!const_SysTable.iSun_IsNew)
             {
               _tableName.disabled=true;
               _txtNotes.disabled=true;
               _txtNotes.value=const_SysTable.Notes;
               //const_TableName=const_SysTable.Notes;     
             }
             else{
               _tableName.disabled=true;
               const_Tableid=NewGuid();
             }
          }

          YAHOO.example.RowDataMod = function () {
        
            //定义表头
            var myColumnDefs = [
            //{ key: "Left", label: "左括符", resizeable: true, formatter: formatLeftText },
            //{ key: "FieldName", label: "左括符", resizeable: true },
            { key: "iSun_Selected", label: "", resizeable: true, formatter: formatCheckBoxText },
            { key: "FieldName", label: "字段名", resizeable: true, formatter: formatField },
            { key:"Notes",label:"字段说明",resizeable: true,formatter: formatNotesText},
            { key: "FiledType", label: "字段类型", resizeable: true, formatter: formatFiledType },
            { key: "Length", label: "长度/精确度", resizeable: true, formatter: formatLengthText },
            { key: "Is_Null", label: "是否允许为空", resizeable: true, formatter: formatIs_Null },
            { key: "Is_ForeignKey", label: "是否为外键", resizeable: true, formatter: formatIs_ForeignKey },
            { key: "ControlsType", label: "控件类型", resizeable: true, formatter: formatControlsType },
            { key: "ColSeq", label: "排序", resizeable: true, formatter: formatColSeqText }
            //{ key: "Right", label: "右括符", resizeable: true, formatter: formatRightText }
          ];
           
            //定义数据源字段名
            myDataSource = new YAHOO.util.DataSource([]);
            myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
            myDataSource.responseSchema = {
                fields: ["TableFieldID","FieldName","TableID", "TableName", "Is_ForeignKey", "FiledType", "Length","Notes","Is_Null","ControlsType","ColSeq","iSun_Selected","iSun_IsNew","MasterTableName"]
            };
            
            //创建表
             myDataTable = new YAHOO.widget.DataTable("container",
                myColumnDefs, myDataSource, {selectionMode:"single"});
            mDataTable = myDataTable;
            var i = 1,
            bReverseSorted = false;

            //排序
            // Track when Column is reverse-sorted, since new data will come in out of order
            var trackReverseSorts = function (oArg) {
                bReverseSorted = (oArg.dir === YAHOO.widget.DataTable.CLASS_DESC);
            };

            //注册事件
            myDataTable.subscribe("rowMouseoverEvent", myDataTable.onEventHighlightRow); 
	        myDataTable.subscribe("rowMouseoutEvent", myDataTable.onEventUnhighlightRow); 
            myDataTable.subscribe("rowClickEvent", myDataTable.onEventSelectRow); 
            //this.myDataTable.subscribe("rowDblclickEvent", onRowDoubleClick);
            myDataTable.subscribe("checkboxClickEvent", function(oArgs){
                var elCheckbox = oArgs.target;
                var oRecord = this.getRecord(elCheckbox);
                oRecord.setData("iSun_Selected",elCheckbox.checked);
            });


                // Set height as a string value 
//	        var myDataTableY = new YAHOO.widget.ScrollingDataTable("container", myColumnDefs, 
//	                myDataSource, {height:"10em"}); 

            // Add/update/delete rows as indicated
            var handleClick = function () {
                // Reset sort
               
                myDataTable.set("sortedBy", null);
            
                index = myDataTable.getRecordSet()._records.length;
                if(const_BlankInstance[0])
                {
                        var _tableName = YAHOO.util.Dom.get("txtTableName");
                        if(const_Tableid!='')
                        {
                            const_BlankInstance[0].TableID=const_Tableid;
                        }
                        if( typeof (parent._MasterTableName) != "undefined")
                        {
                           const_BlankInstance[0].MasterTableName= parent._MasterTableName;
                        }
                              
                        const_BlankInstance[0].TableName=_tableName.value;
                        const_BlankInstance[0].Length = "50";
                        const_BlankInstance[0].Is_ForeignKey ="N" ;
                        const_BlankInstance[0].Is_Null = "Y";

                        const_BlankInstance[0].FieldName = '';
                        const_BlankInstance[0].Notes ='' ;
                        const_BlankInstance[0].iSun_IsNew = true;

                }
                var entity = const_BlankInstance;
                myDataTable.addRows(entity, index);

                YAHOO.log("Could not continue due to invalid index.");
              }


             var handleDefaultPropertyValues=function () 
             {
               if(isAddDefault=='1')
               {
                  if(const_SysTable.iSun_IsNew)
                  {
                  //debugger;
                       $.each(anObject,function(name,value) { 
                           if(!checkFiledName(value)){
                              if(parent.getTableType()=="Details")
                              {
                                if(!iExistDefaultField())
                                {
                                  AddDefaultProperty (name,value,false);
                                 }
                              }else{AddDefaultProperty (name,value,false);}
                            }
                        });
                        if(parent.getTableType()=="Details")
                        {
                                index = myDataTable.getRecordSet()._records.length;
                                if(const_BlankInstance[0])
                                {
                                        var _tableName = YAHOO.util.Dom.get("txtTableName");
                                         if(const_Tableid!='')
                                        {
                                            const_BlankInstance[0].TableID=const_Tableid;
                                        }
                                       if( typeof (parent._MasterTableName) != "undefined")
                                        {
                                           const_BlankInstance[0].MasterTableName= parent._MasterTableName;
                                        }
                                        const_BlankInstance[0].FiledType="uniqueidentifier";
                                        const_BlankInstance[0].TableName=_tableName.value;;
                                        const_BlankInstance[0].Length = "16";
                                        const_BlankInstance[0].Is_ForeignKey ="Y" ;
                                        const_BlankInstance[0].Is_Null = "Y";
                                        const_BlankInstance[0].FieldName = parent._MasterTableName+"ID";
                                        const_BlankInstance[0].Notes ="明细表外键" ;
                                        const_BlankInstance[0].iSun_IsNew = false;
                  
                                }
                                var entity = const_BlankInstance;
                                myDataTable.addRows(entity, index);

                                index = myDataTable.getRecordSet()._records.length;
                                if(const_BlankInstance[0])
                                {
                                        var _tableName = YAHOO.util.Dom.get("txtTableName");
                                         if(const_Tableid!='')
                                        {
                                            const_BlankInstance[0].TableID=const_Tableid;
                                        }
                                       if( typeof (parent._MasterTableName) != "undefined")
                                        {
                                           const_BlankInstance[0].MasterTableName= parent._MasterTableName;
                                        }
                                        const_BlankInstance[0].FiledType="int";
                                        const_BlankInstance[0].TableName=_tableName.value;;
                                        const_BlankInstance[0].Length = "4";
                                        const_BlankInstance[0].Is_ForeignKey ="N" ;
                                        const_BlankInstance[0].Is_Null = "N";
                                        const_BlankInstance[0].FieldName = "RecID";
                                        const_BlankInstance[0].Notes ="明细表流水号" ;
                                        const_BlankInstance[0].iSun_IsNew = false;
                  
                                }
                                var entity = const_BlankInstance;
                                myDataTable.addRows(entity, index);
                          }
                   } 
               }  
             }
            AddPropertyByLength = function (PropertyName,Property,Length,isNew) {
                // Reset sort
               //checkFiledName(v)


               // myDataTable.set("sortedBy", null);

                index = myDataTable.getRecordSet()._records.length;
                if(const_BlankInstance[0])
                {
                        var _tableName = YAHOO.util.Dom.get("txtTableName");
                         if(const_Tableid!='')
                        {
                            const_BlankInstance[0].TableID=const_Tableid;
                        }
                       if( typeof (parent._MasterTableName) != "undefined")
                        {
                           const_BlankInstance[0].MasterTableName= parent._MasterTableName;
                        }
                        const_BlankInstance[0].TableName=_tableName.value;;
                        const_BlankInstance[0].Length = Length;
                        const_BlankInstance[0].Is_ForeignKey ="N" ;
                        const_BlankInstance[0].Is_Null = "Y";
                        const_BlankInstance[0].FieldName = Property;
                        const_BlankInstance[0].Notes =PropertyName ;
                        const_BlankInstance[0].iSun_IsNew = isNew;
                        const_BlankInstance[0].ControlsType="textfield";

                  
                }
                var entity = const_BlankInstance;
                myDataTable.addRows(entity, index);

                YAHOO.log("Could not continue due to invalid index.");
              }
           AddDefaultProperty = function (PropertyName,Property,isNew) {
                // Reset sort
               //checkFiledName(v)


               // myDataTable.set("sortedBy", null);

                index = myDataTable.getRecordSet()._records.length;
                if(const_BlankInstance[0])
                {
                        var _tableName = YAHOO.util.Dom.get("txtTableName");
                         if(const_Tableid!='')
                        {
                            const_BlankInstance[0].TableID=const_Tableid;
                        }
                       if( typeof (parent._MasterTableName) != "undefined")
                        {
                           const_BlankInstance[0].MasterTableName= parent._MasterTableName;
                        }
                        const_BlankInstance[0].TableName=_tableName.value;;
                        const_BlankInstance[0].Length = "50";
                        const_BlankInstance[0].Is_ForeignKey ="N" ;
                        const_BlankInstance[0].Is_Null = "Y";
                        const_BlankInstance[0].FieldName = Property;
                        const_BlankInstance[0].Notes =PropertyName ;
                        const_BlankInstance[0].iSun_IsNew = isNew;
                        const_BlankInstance[0].ControlsType="textfield";

                        if(Property.indexOf('ID') >= 0)
                        {
                         const_BlankInstance[0].ControlsType="Hidden";
                        }
                        if(Property.indexOf('bpmTitle') >= 0)
                        {
                         const_BlankInstance[0].Length="100";
                        }
                  
                }
                var entity = const_BlankInstance;
                myDataTable.addRows(entity, index);

                YAHOO.log("Could not continue due to invalid index.");
              }
            var fnDelete = function()
            {
                
                var recordID = myDataTable.getSelectedRows()[0];
                var list = myDataTable.getRecordSet()._records;

                dl = [];
                for (var i = 0; i < list.length; i++) {
                    //this.getRecordSet()._records[0]._oData["BarItem"]
                    if (list[i]._oData["iSun_Selected"] == true) {
                        
                        dl.push(list[i]._sId); //获取行ID；
                    }
                }

                 if (dl.length == 0) 
                 {
                            myDataTable.deleteRow(recordID);
                 }
                 else 
                 {
                        for (var i = 0; i < dl.length; i++) 
                        {
                            myDataTable.deleteRow(dl[i]);
                        }
                 }  
            }

     
     

            var btnAdd = new YAHOO.widget.Button("btnAddNew");
            btnAdd.on("click", handleClick);
            var btnSave = new YAHOO.widget.Button("");
            btnSave.on("click",Save);
            var btnDel = new YAHOO.widget.Button("btnDelete");
            btnDel.on("click",fnDelete);
            
            SetFormValue();
            
        
           
            handleDefaultPropertyValues();
         
            return {
                ds: myDataSource,
                dt: myDataTable
              };
            

        } ();

       
    });

 

    function TableFieldItem() {
                this.TableFieldID = '';
                this.TableID = '';
                this.TableName = '';
                this.Is_ForeignKey = '';
                this.FieldName = '';
                this.FiledType = '';
                this.Length = '';
                //this.Is_CustomDefine = '';
                this.Is_Null = '';
                this.Notes = '';
                this.MasterTableName = '';
            }
         function sysTable() {
                this.TableID = '';
                this.TableName = '';
                this.AlaisName = '';
                this.Is_View = '';
                this.Notes = '';
            }
         function TableFieldFormItem() {
                this.ColDesc = '';
                this.ColName = '';
                this.CType = '';
                this.CanNull = '';
                this.ControlsType = '';
                this.ColSeq = '';
            }
         var iExistDefaultField=function(fieldName)
         {             
           var _iexist=false;
            $.each(anObject,function(name,value) { 
                if(fieldName==value)
                {
                   _iexist=true;
                   return false;
                }
            });
           return _iexist
         }
         var iExistField=function(fieldName){
            var WorkFlowObject = { '流程模板ID':'WorkFlowId', '流程实例ID':'WorkFlowInsId', '流程模板任务ID':'WorkTaskId','流程任务实例ID':'WorkTaskInsId'};
             
            var _iexist=false;
             if(parent.getTableType()=="Details")
              {
                 WorkFlowObject=anObject;
              }
    
           if(fieldName=='ID'){
             _iexist=true;
             return _iexist;
            }else{
            $.each(WorkFlowObject,function(name,value) { 
                if(fieldName==value){
                   _iexist=true;
                   return false;
                }
            });
          }
         return _iexist
         
         }
         var setTableField=function(){
                var list =myDataTable.getRecordSet()._records;
                var elist = [];
                fieldList=[];
                const_PrimaryKeyItems='';
                for(var i=0;i<list.length;i++)
                {
                    if(list[i]._oData["TableFieldID"]==""||list[i]._oData["TableFieldID"]=="00000000-0000-0000-0000-000000000000")
                    {
                        var _items =new TableFieldItem();
                        _items.TableFieldID = list[i]._oData.TableFieldID;
                        _items.TableID =list[i]._oData.TableID;
                        _items.TableName = list[i]._oData.TableName;
                        _items.Is_ForeignKey =list[i]._oData.Is_ForeignKey;
                        _items.FieldName = list[i]._oData.FieldName;
                        _items.FiledType = list[i]._oData.FiledType;
                        _items.Length = list[i]._oData.Length;
                        //_items.Is_CustomDefine =list[i]._oData.Is_CustomDefine;
                        _items.Is_Null = list[i]._oData.Is_Null;
                        _items.Notes =list[i]._oData.Notes;
                        _items.MasterTableName=list[i]._oData.MasterTableName;
                        elist.push(_items);
                    }
                        if(list[i]._oData.Is_ForeignKey=='Y')
                        {
                           if(const_PrimaryKeyItems==''){const_PrimaryKeyItems=list[i]._oData.FieldName}
                           else{ const_PrimaryKeyItems+=','+list[i]._oData.FieldName;}
                        }
                        
                        var defaultField=iExistField(list[i]._oData.FieldName);
                        if(!defaultField)
                        {
                            var _Formitems =new TableFieldFormItem();
                            _Formitems.ColDesc = list[i]._oData.Notes;
                            _Formitems.ColName =list[i]._oData.FieldName;
                             switch(list[i]._oData.FiledType) {
                             case "varchar":
                                _Formitems.CType="string";
                                break;
                             case "uniqueidentifier":
                                _Formitems.CType="string";
                                break;
                            case "numeric":
                                _Formitems.CType="decimal";
                                break;
                             case "ntext":
                                _Formitems.CType="string";
                                break;
                             case "nchar":
                                _Formitems.CType="string";
                                break;
                             case "real":
                                _Formitems.CType="string"; 
                                break;
                            case "float":
                                _Formitems.CType="decimal"; 
                                break;
                             case "binary":
                                _Formitems.CType="string"; 
                                break;
                             case "date":
                                _Formitems.CType="string";
                                break;
                             case "smalldatetime":
                                _Formitems.CType="string";
                                break;
                            case "bigint":
                                _Formitems.CType="int";
                                break;
                             case "datetime":
                                _Formitems.CType="datetime"
                                break;
                             case "int":
                                _Formitems.CType="int"; 
                                break;
                             case "bit":
                                _Formitems.CType="string"; 
                                break;
                            case "char":
                                _Formitems.CType="string";
                                break;
                             case "image":
                                _Formitems.CType="string";
                                break;
                             }
                       
                            if( list[i]._oData.Is_Null=="Y"){_Formitems.CanNull="empty";}
                            else{_Formitems.CanNull="required";}
                       
                            _Formitems.ControlsType = list[i]._oData.ControlsType;
                            _Formitems.ColSeq = list[i]._oData.ColSeq;

                            fieldList.push(_Formitems);
                        }
                }

                
                var jsonStr = YAHOO.lang.JSON.stringify(elist);
               

                var json =jsonStr.replace(/&/g,"[A]").replace(/'/g,"''");
                //var json =$.toJSON(instance[0]).replace(/'/g,"[B]").replace(/\n/g,'[BR]');
                $("#jsonDataContent").val(json);

             // return "?r=" + Math.random() + "&action=setTableStruc&functionid="+const_FunctionId+"&entity="+const_EntityName+"&json=" + encodeURI(jsonStr.replace(/&/g,"[A]").replace(/'/g,"''"));
           }
         var setSysTable=function(){    
             if(const_SysTable.iSun_IsNew)
             {
             //const_Table
               var _notes = YAHOO.util.Dom.get("txtNotes");
               var _tableName = YAHOO.util.Dom.get("txtTableName");
               var _table =new sysTable();
                _table.TableID =const_Tableid;
                _table.TableName= _tableName.value;
                const_TableName= _notes.value;
                const_Table=_tableName.value;
                _table.AlaisName= _tableName.value;
                _table.Is_View="N";
                _table.Notes =_notes.value;

                 var jsonStr = YAHOO.lang.JSON.stringify(_table);
                return "?r=" + Math.random() + "&entity=SysTable&action=insert&json=" + encodeURI(jsonStr.replace(/&/g,"[A]").replace(/'/g,"''"));
             }
          }

            var Save= function ()
            { 
                 
                 var errMsg = parent.checkValue();
                 errMsg+=checkValue();
                if (errMsg == '') 
                {
                 SaveSysTable(const_SysTable.iSun_IsNew,setSysTable(),setTableField()); //是否是新表
                }
                  else { alert(errMsg); }
          
            }
     
           //保存
            var SaveTableField = function (urlData)
            {
              
                    url = "../Extend/AjaxData/DataSave.aspx";
                    var msg="0";
                    var SaveUrl =url+urlData
                    YAHOO.util.Connect.asyncRequest('POST', SaveUrl, {
                        success: function (res) {
                            try {
                                var str = res.responseText;
                                if(str=="1"){
                                    //alert("数据保存成功");
                                    parent.Save(fieldList,const_Table,const_PrimaryKeyItems);
                                    //parent.closeWin();
                                }
                                else
                                {
                                    alert(str+"\n"+"数据保存失败!");
                                     window.location.reload();
                                }
                            }
                            catch (e) {
                            }
                            finally {
                            }
                        },
                        failure: function (error) {
                            alert("数据错误：" + error.statusText);
                             window.location.reload();
                        }
                    }, null);
                }


        var trySave = function()   
        {
            // argument formId can be the id or name attribute value of the
            // HTML form, or an HTML form object.
            url = "../Extend/AjaxData/DataSave.aspx";

            var formObject = document.getElementById('form2');
            YAHOO.util.Connect.setForm(formObject);
            // This example facilitates a POST transaction.  The POST data(HTML form)
            // are initialized when calling setForm(), and it is automatically
            // included when calling asyncRequest.
            var cObj = YAHOO.util.Connect.asyncRequest('POST',url+"?flag=1&action=setTableStruc&functionid="+const_FunctionId+"&entity="+const_EntityName,callback);
        }
        
        var responseSuccess = function (res) {
                    try {
    
                        var str = res.responseText;
                        //var obj = eval(str);
                 
                        if(str=="1"){
                            //alert("数据保存成功");
                            parent.Save(fieldList,const_Table,const_PrimaryKeyItems);
                            parent.closeWin();
                        }
                        else
                        {
                            alert(str+"\n"+"数据保存失败!");
                             window.location.reload();
                        }
                    }
                    catch (e) {

                    }
                    finally {
                    }
        };
        var responseFailure =function (error) {
                    alert("数据错误：" + error.statusText);
                      window.location.reload();
        }
 
        // Create a callback object that defines success and failure
        // handlers, and instructs Connection Manager to use the
        // Flash transport by defining the xdr property and setting
        // it to true.
       var  callback = {
            success:responseSuccess,
            failure:responseFailure
        };
            var SaveSysTable = function (IsNew,urlTableData,urlFieldData)
            {

                    
                    DIF.IsTableExists.init(const_TableName)
                    var isExistsTable=DIF.IsTableExists.IsExists();
                    if(isExistsTable=='0'){
                        url = "../Extend/AjaxData/DataSave.aspx";
                        var SaveUrl =url+urlTableData;
                        YAHOO.util.Connect.asyncRequest('POST', SaveUrl, {
                            success: function (res) {
                                try {
                                    var str = res.responseText;
                                    if(str=="1")
                                    {
                                      //SaveTableField(urlFieldData); 
                                      parent.init_selectTable();
                                      //parent.disableAddTable(true);
                                      trySave();
                                     
                                    }
                                    else
                                    {
                                        alert(str+"\n"+"数据保存失败!");
                                        window.location.reload();

                                    }
                                }
                                catch (e) {
                                }
                                finally {
                                }
                            },
                            failure: function (error) {
                                alert("数据错误：" + error.statusText);
                                  window.location.reload();
                            }
                        }, null);
                    }else{ trySave();}
                }


            var checkValue = function () {
            var ErrMsg = '';
            var setTable = YAHOO.util.Dom.get("txtTableName");
            if (checkIsEmpty(setTable)) { ErrMsg = ErrMsg + "您选择入的表名为空！请重新选择."; }

            return ErrMsg;
        }
        var checkIsEmpty = function (obj) {
            var text = obj.value
            var isEmpty = false;
            if (text == '') { isEmpty = true; }
            else { isEmpty = false; }
            return isEmpty;
        }

    //值改变事件
    var ChangeEvent = function(oArgs){
     
        var selectID = mDataTable.getSelectedRows()[0];
        var f = oArgs.name;
        //alert(f);
        var v = oArgs.value;
        //alert(v);
        //debugger;
        if(checkFiledName(v,selectID))
        {
            alert("您输入的字段名\""+v+"\"已经存在，请重新输入");
        }
        if(f=='ControlsType')
        {
          if(v=='textarea'){setLengthValue(oArgs);}
          switch (v) 
          {
            case 'textarea':
               setLengthValue(oArgs);
               break;
            case 'pos':
                    if(!checkFiledName('TRFDeptID'))
                    {
                         AddDefaultProperty ('TRF部门编号','TRFDeptID',true);
                    }
                    if(!checkFiledName('TRFDeptName'))
                    {
                        AddDefaultProperty ('TRF部门名称','TRFDeptName',true);
                    }
                    if(!checkFiledName('txtTRFDeptID'))
                    {
                        AddDefaultProperty ('TRF部门名称','txtTRFDeptID',true);
                    }
                    if(!checkFiledName('TRFPostName'))
                    {
                        AddDefaultProperty ('TRF岗位名称','TRFPostName',true);
                    }
                     if(!checkFiledName('TRFPostID'))
                    {
                        AddDefaultProperty ('TRF岗位编号','TRFPostID',true);
                    }
               break;
               case 'dep':
                    if(!checkFiledName('TRFDeptID'))
                    {
                        AddDefaultProperty ('TRF部门编号','TRFDeptID',true);
                    }
                    if(!checkFiledName('txtTRFDeptID'))
                    {
                        AddDefaultProperty ('TRF部门名称','txtTRFDeptID',true);
                    }
               break;
              case 'workflowfell':
            
                    $($($($(arguments[0])[0])[0].parentElement)[0].parentElement.parentElement).find('[name=Length]').val('1000');
                    //$($($($(arguments[0])[0])[0].parentElement)[0].parentElement.parentElement).find('[name=ControlsType]').val('Hidden');
                    
                    var PropertyName=$($($($(arguments[0])[0])[0].parentElement)[0].parentElement.parentElement).find('[name=Notes]').val();
                    var PropertyValue=$($($($(arguments[0])[0])[0].parentElement)[0].parentElement.parentElement).find('[name=FieldName]').val();
                     var valValue=PropertyName+'名称';
                     var _txtName='txt'+PropertyValue;
                    if(!checkFiledName(_txtName))
                    {
                        AddPropertyByLength (valValue,_txtName,'1000',true);
                    }
                    $($($($(arguments[0])[0])[0].parentElement)[0].parentElement.parentElement).find('[name=Notes]').val(PropertyName+'编号');
               break;
          }
        }
        setValue(f,v);
    }


//    if(!checkFiledName(value)){
//                              if(parent.getTableType()=="Details")
//                              {
//                                if(!iExistDefaultField())
//                                {
//                                  AddDefaultProperty (name,value);
//                                 }
//                              }else{AddDefaultProperty (name,value);}
//                            }



    var setLengthValue=function(){setValue('Length','500');
      $($($($(arguments[0])[0])[0].parentElement)[0].parentElement.parentElement).find('[name=Length]').val('500');
      //alert((arguments[0]).parent[0].tagName);
    }
 
    ///f=字段名 v=值
    var setValue = function(f,v){
        var recordID = mDataTable.getSelectedRows()[0];
        var record = mDataTable.getRecord(recordID);
        record._oData[f]=v;    
    }

    var  checkFiledName=function(v,id){
                var isExistFiled=false
                var list=myDataTable.getRecordSet()._records;
                for(var i=0;i<list.length;i++)
                {
                     if(list[i]._sId!=id)
                     {
                          if(list[i]._oData.FieldName.toLowerCase()==v.toLowerCase())
                          {
                            isExistFiled=true;
                            continue;
                          }
                      }

                }
                return isExistFiled;
    }
    
    var ChangeSolution = function(obj){
        //alert(obj.value);
        for(var i=0;i<const_SolutionList.length;i++){
            if(const_SolutionList[i].QueryId==obj.value)
            {
                SetFormValue(const_SolutionList[i]);
            }
        }

        //const_SolutionList 
    }
    
    var SetFormValue = function(){
     
        var arr = const_SolutionList;
        myDataSource.liveData = arr;
        mDataTable.getDataSource().sendRequest(null,
        {success: mDataTable.onDataReturnInitializeTable},
        mDataTable);

      }

    </script>
    <!--END SOURCE CODE FOR EXAMPLE =============================== -->
</body>
</html>
